package cn.luyou.admin.controller;

import cn.luyou.admin.common.Result;
import cn.luyou.admin.entity.ExamRule;
import cn.luyou.admin.service.ExamRuleService;

import cn.luyou.admin.utils.BaseContext;
import com.baomidou.mybatisplus.core.metadata.IPage;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.service.annotation.GetExchange;

@RestController
@RequestMapping("/exam-rules")
public class ExamRuleController {

    @Autowired
    private ExamRuleService examRuleService;

    @GetMapping
    public Result<IPage<ExamRule>> getRules(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        return Result.success(examRuleService.getRules(pageNum, pageSize, keyword));
    }

    @PostMapping
    public Result<ExamRule> addRule(@RequestBody @Valid ExamRule rule, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        rule.setCreatedBy(BaseContext.getCurrentId());
        return Result.success(examRuleService.addRule(rule));
    }

    @PutMapping("/{id}")
    public Result<Void> updateRule(@PathVariable Long id, @RequestBody @Valid ExamRule rule) {
        rule.setId(id);
        examRuleService.updateRule(rule);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteRule(@PathVariable Long id) {
        examRuleService.deleteRule(id);
        return Result.success();
    }

    @PutMapping("/{id}/status")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        examRuleService.updateStatus(id, status);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<ExamRule> getRule(@PathVariable Long id) {
        return Result.success(examRuleService.getRuleById(id));
    }
}
